// 1. 基本数据类型
let username: string = "张三";
let age: number = 25;
let isStudent: boolean = true;
let hobbies: string[] = ["读书", "运动"];
let favoriteNumber: number | string = "7"; 

// 2. 接口（定义对象结构）
interface User {
    name: string;
    age: number;
    isStudent?: boolean; 
}

interface Product {
    id: number;
    name: string;
    price: number;
}

// 3. 交叉类型（合并多个类型）
type UserProduct = User & { product: Product }; 

// 4. 对象类型
const user: User = {
    name: username,
    age: age,
    isStudent: isStudent
};

const product: Product = {
    id: 101,
    name: "TypeScript入门书",
    price: 59.9
};

// 5. 使用交叉类型
const userWithProduct: UserProduct = {
    ...user,
    product: product
};

// 页面加载后执行
window.onload = () => {
    // 获取DOM元素（可能为null，需要类型判断）
    const userInfoDiv = document.getElementById('userInfo');
    const productInfoDiv = document.getElementById('productInfo');
    const messageDiv = document.getElementById('message');

    // 类型守卫：确保元素存在
    if (userInfoDiv instanceof HTMLElement) {
        userInfoDiv.innerHTML = `
            <h3>用户信息</h3>
            <p>姓名: ${user.name}</p>
            <p>年龄: ${user.age}</p>
            <p>是否学生: ${user.isStudent ? '是' : '否'}</p>
        `;
        userInfoDiv.style.color = 'darkblue';
    }

    if (productInfoDiv instanceof HTMLElement) {
        productInfoDiv.innerHTML = `
            <h3>产品信息</h3>
            <p>ID: ${product.id}</p>
            <p>名称: ${product.name}</p>
            <p>价格: ¥${product.price}</p>
        `;
        productInfoDiv.style.color = 'darkgreen';
    }

    // 联合类型使用示例
    if (messageDiv instanceof HTMLElement) {
        let message: string;
        // 类型判断（联合类型的类型守卫）
        if (typeof favoriteNumber === 'string') {
            message = `最喜欢的数字是字符串形式: ${favoriteNumber}`;
        } else {
            message = `最喜欢的数字是数字形式: ${favoriteNumber}`;
        }
        messageDiv.textContent = message;
        messageDiv.style.fontWeight = 'bold';
    }
};